<script setup lang="ts">
import TileItem from '@/components/tiles/item/TileItem.vue'
import {onMounted, ref, watchEffect} from 'vue';

let previousPlayedTiles = ref(null);
const props = defineProps({
    tiles: { type: Array<string>, required: true }
}) 

let transformStyleColArr = ref(new Array<Array<string>>());

let tilesColArr = ref(new Array<Array<string>>());
let colTransformStyles = ref(new Array<string>());

function loadStyles() {
  transformStyleColArr.value = new Array();
  tilesColArr.value = new Array();
  colTransformStyles.value = new Array();
  if (previousPlayedTiles.value == null) {
    return;
  }
  // 基础旋转角度
  let baseTransformStyle = "rotateX(-30deg) rotateY(260deg) rotateX(90deg)";
  // 一列最多容纳的麻将
  let oneColCount = Math.floor((previousPlayedTiles as any).value.offsetHeight / 64);
  // 总列数
  let totalCol = Math.ceil(props.tiles.length / oneColCount);
  // 判断数值是否是正负无穷大，如果是无穷大，则认为是无效
  if (!Number.isFinite(totalCol)) {
    return;
  }
  for (var i=0; i<totalCol; i++) {
    // 当前列的麻将
    let colTiles = new Array();
    let transformStyles = new Array();
    let startIndex = i*oneColCount;
    let endIndex = oneColCount * (i+1);
    for (let j = startIndex; j < endIndex; j++) {
      let secondIndex = j - startIndex;
      if (j < props.tiles.length) {
        colTiles.push(props.tiles[j])
        transformStyles[secondIndex] = (baseTransformStyle  +" translateY(" + (secondIndex * 9) + "px)" + " translateZ(" + (secondIndex * 45) + "px)");
      } else {
        break;
      }
    }
    transformStyleColArr.value[i] = transformStyles;
    tilesColArr.value[i] = colTiles;
    colTransformStyles.value[i] = `translateY(${(i*-5)}px) translateX(${i*-16}px)`
  }
}

onMounted(() => {
  loadStyles();
})
watchEffect(() => {
  loadStyles();
})
</script>

<template>
  <div class="previous-played-tiles" ref="previousPlayedTiles">
    <div class="previous-played-tiles-col" v-for="(cvalue, cindex) in tilesColArr" :key="cindex" :style="{transform: colTransformStyles[cindex], 'z-index': 2100 - cindex}">
      <template v-for="(tileItem, index) in cvalue" :key="index">
        <TileItem :code="(tileItem as string)" :transformStyle="transformStyleColArr[cindex][index]" :scale="0.8"></TileItem>
      </template>
    </div>
  </div>
</template>

<style scoped lang="scss">
.previous-played-tiles {
  display: flex;
  flex-direction: row-reverse;
  // justify-content: flex-start;
}
</style>
